package org.funtester.performance.books.chapter03.section2;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class TheadPoolForTpsModel {

    public static void main(String[] args) {
        ThreadFactory threadFactory = new ThreadFactory() {// 创建一个线程工厂

            AtomicInteger index = new AtomicInteger();// 线程安全的线程编号

            @Override
            public Thread newThread(Runnable r) {// 重写创建线程方法
                Thread thread = new Thread(r);// 创建线程
                thread.setName("线程-" + index.incrementAndGet());// 设置线程名称
                return thread;// 返回创建的线程
            }
        };
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 200, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), threadFactory);// 创建线程池

        for (int i = 0; i < 8; i++) {// 向线程池提交8个任务
            threadPoolExecutor.execute(new Runnable() {// 提交任务
                @Override
                public void run() {// 任务执行逻辑
                    System.out.println(System.currentTimeMillis() + "  线程池中的线程名称: " + Thread.currentThread().getName());// 输出线程名称
                    try {
                        Thread.sleep(100);// 模拟任务执行时间
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);// 抛出运行时异常
                    }
                }
            });
        }
        threadPoolExecutor.shutdown();// 关闭线程池

    }

}
